<template>
	<el-upload class="avatar-uploader" :action="action" :show-file-list="false" :on-success="handleUploadSuccess"
		:on-error="handleUploadError" :before-upload="beforeImageUpload" accept="image/*" :headers="headers"
		:data="{ type: type }">
		<img v-if="value" :src="value" class="avatar">
		<i v-else class="el-icon-plus avatar-uploader-icon"></i>
	</el-upload>
</template>

<script>
export default {
	data() {
		return {
			headers: { Authorization: `Bearer ${sessionStorage.access_token}` },
			imageUrl: '',
		}
	},
	props: {
		// 上传图片
		value: {
			type: String,
		},
		action: {
			type: String,
			default: `${process.env.VUE_APP_SERVER}/upload/common`,
		},
		// 上传图片类型
		type: {
			type: String,
			default: 'common',
		},
	},
	methods: {
		// 上传之前的检查
		beforeImageUpload(file) {
			console.log(file);
			let reg = /^image\/(jpeg||png)$/;
			const isImage = reg.test(file.type);
			const isLt2M = file.size / 1024 / 1024 < 2;

			if (!isImage) {
				this.$message.error('上传图片只能是 JPG/PNG 格式!');
			}
			if (!isLt2M) {
				this.$message.error('上传图片大小不能超过 2MB!');
			}
			return isImage && isLt2M;
		},
		// 上传失败
		handleUploadError(err, file, fileList) {
			let { status, message } = err;
			switch (status) {
				case 400:
					let { status, msg } = JSON.parse(message);
					// 信息提示
					this.$message.error(msg);
					break;
				case 401:
					let { code } = JSON.parse(message);
					// 信息提示
					this.$message.error(`错误代码：401，${code},请重新登陆账户！`);
					break;
				default:
					break;
			}
		},
		// 上传成功
		handleUploadSuccess({ status, msg, src }, file) {
			if (status) {
				// 预览图像
				this.$emit('input', src);
				// 信息提示
				this.$message.success(msg);
			}
		},
	}
}
</script>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

.avatar-uploader .el-upload:hover {
	border-color: #409EFF;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}

.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
